local task = {}

-- 每10秒打印一次lua和sys内存占用情况
sys.timerLoopStart(function()
    log.info("lua内存占用情况：", rtos.meminfo())
    log.info("sys内存占用情况：", rtos.meminfo("sys"))
    log.info("IP地址：", socket.localIP(socket.LWIP_GP))
end, 60000)

-- 初始化L298N控制引脚
local left_ctrl, right_ctrl = config.gpio_ctrl() -- 左右转控制引脚 对应L298N的IN1和IN2
local up_ctrl, down_ctrl = config.gpio_run() -- 移动控制引脚 对应L298N的IN3和IN4

-- 配置L298N控制引脚为输出模式并拉低电平
gpio.setup(left_ctrl, 0, gpio.PULLDOWN)
gpio.setup(right_ctrl, 0, gpio.PULLDOWN)
gpio.setup(up_ctrl, 0, gpio.PULLDOWN)
gpio.setup(down_ctrl, 0, gpio.PULLDOWN)

-- 根据MQTT消息控制L298N
local task = {
    ["up"] = function()
        print("上")
        gpio.set(up_ctrl, gpio.HIGH)
        gpio.set(down_ctrl, gpio.LOW)
    end,
    ["down"] = function()
        print("下")
        gpio.set(up_ctrl, gpio.LOW)
        gpio.set(down_ctrl, gpio.HIGH)
    end,
    ["left"] = function()
        print("左")
        gpio.set(left_ctrl, gpio.HIGH)
        gpio.set(right_ctrl, gpio.LOW)
    end,
    ["right"] = function()
        print("右")
        gpio.set(left_ctrl, gpio.LOW)
        gpio.set(right_ctrl, gpio.HIGH)
    end,
    ["stop"] = function()
        print("停止")
        gpio.set(left_ctrl, gpio.LOW)
        gpio.set(right_ctrl, gpio.LOW)
        gpio.set(up_ctrl, gpio.LOW)
        gpio.set(down_ctrl, gpio.LOW)
    end
}

-- 任务代码
sys.taskInit(function()
    while true do
        local ret, msg = sys.waitUntil("mqtt_recv")
        if msg then
            log.info("收到mqtt消息：", msg, type(msg))
            local f = task[msg]
            if f then
                f(msg)
            else
                log.warn("未知命令：", msg)
            end
            f = nil
        end
    end
end)

return task